package com.ruoyi.members.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.CommonConstants;
import com.ruoyi.common.constant.MembersConstants;
import com.ruoyi.common.constant.UnionConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.MembersStatus;
import com.ruoyi.common.enums.UnionsStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.members.domain.SysMembers;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.members.mapper.SysUnionMembersMapper;
import com.ruoyi.members.domain.SysUnionMembers;
import com.ruoyi.members.service.ISysUnionMembersService;

/**
 * 基层工会会员Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@Service
public class SysUnionMembersServiceImpl extends ServiceImpl<SysUnionMembersMapper, SysUnionMembers> implements ISysUnionMembersService
{
    @Autowired
    private SysUnionMembersMapper sysUnionMembersMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService sysRoleService;
    /**
     * 查询基层工会会员
     * 
     * @param membersId 基层工会会员主键
     * @return 基层工会会员
     */
    @Override
    public SysUnionMembers selectSysUnionMembersByMembersId(Long membersId)
    {
        return sysUnionMembersMapper.selectSysUnionMembersByMembersId(membersId);
    }

    /**
     * 查询基层工会会员列表
     * 
     * @param sysUnionMembers 基层工会会员
     * @return 基层工会会员
     */
    @Override
    public List<SysUnionMembers> selectSysUnionMembersList(SysUnionMembers sysUnionMembers)
    {
        return sysUnionMembersMapper.selectSysUnionMembersList(sysUnionMembers);
    }

    /**
     * 新增基层工会会员
     * 
     * @param sysUnionMembers 基层工会会员
     * @return 结果
     */
    @Override
    public int insertSysUnionMembers(SysUnionMembers sysUnionMembers)
    {
        sysUnionMembers.setCreateTime(DateUtils.getNowDate());
        return sysUnionMembersMapper.insertSysUnionMembers(sysUnionMembers);
    }

    /**
     * 修改基层工会会员
     * 
     * @param sysUnionMembers 基层工会会员
     * @return 结果
     */
    @Override
    public int updateSysUnionMembers(SysUnionMembers sysUnionMembers)
    {
        sysUnionMembers.setUpdateTime(DateUtils.getNowDate());
        return sysUnionMembersMapper.updateSysUnionMembers(sysUnionMembers);
    }

    /**
     * 批量删除基层工会会员
     * 
     * @param membersIds 需要删除的基层工会会员主键
     * @return 结果
     */
    @Override
    public int deleteSysUnionMembersByMembersIds(Long[] membersIds)
    {
        return sysUnionMembersMapper.deleteSysUnionMembersByMembersIds(membersIds);
    }

    /**
     * 删除基层工会会员信息
     * 
     * @param membersId 基层工会会员主键
     * @return 结果
     */
    @Override
    public int deleteSysUnionMembersByMembersId(Long membersId)
    {
        return sysUnionMembersMapper.deleteSysUnionMembersByMembersId(membersId);
    }

    /**
     * 添加会员
     * @param sysUnionMembers
     * @return
     */

    @Override
    public UnionsStatus saveUnionsMembers(SysUnionMembers sysUnionMembers) {
        //会员 - 工号不能重复 （会员表 工号字段）
        List<SysUnionMembers> list = list(new LambdaQueryWrapper<>(SysUnionMembers.class).eq(SysUnionMembers::getMembersNum,sysUnionMembers.getMembersNum()));
        if (list.size() > 0){
            return UnionsStatus.UNIONS_MEMBERS_EXIST;
        }
        //基层工会 - 角色是否存在 (角色表 姓名字段)
        SysRole sysRole = new SysRole();
        sysRole.setRoleName(UnionConstants.UNION_CHAIRMAN);
        List<SysRole> sysRoles = sysRoleService.selectRoleList(sysRole);
        if (sysRoles.size() == 0){
            return UnionsStatus.UNION_CHAIRMAN_ROLE_NOT_EXIST;
        }

        //添加用户 - （用户表 账号字段） -没有则新增，有不新增
        List<SysUser> list1 = sysUserService.list(new LambdaQueryWrapper<>(SysUser.class).eq(SysUser::getUserName, sysUnionMembers.getMembersNum()));
        Long userId = 0L;
        if (list1.size() > 0){
            userId = list1.get(0).getUserId();
        }
        if (list1.isEmpty()){
            //新增用户 用户表
            SysUser user = SysUser.builder()
                    .userName(sysUnionMembers.getMembersNum().toString())
                    .nickName(sysUnionMembers.getMembersName())
                    .deptId(MembersConstants.NO_DEPT)
                    .phonenumber(sysUnionMembers.getMembersTel())
                    .sex(sysUnionMembers.getMembersSex())
                    .password(SecurityUtils.encryptPassword(CommonConstants.DEFAULT_PASSWORD))
                    .build();
            user.setCreateBy(SecurityUtils.getUsername());
            boolean save = sysUserService.save(user);
            if (!save){
                return UnionsStatus.USER_ADD_FAIL;
            }
            userId = user.getUserId();
        }


        //添加会员
        sysUnionMembers.setCreateBy(SecurityUtils.getUsername());
        sysUnionMembers.setUserId(userId);
        boolean save1 = save(sysUnionMembers);
        if (!save1){
            return UnionsStatus.UNIONS_MEMBERS_ADD_FAIL;
        }

        //用户角色分配
        sysUserService.insertUserAuth(userId, new Long[]{sysRoles.get(0).getRoleId()});


        return UnionsStatus.SUCCESS;
    }

    @Override
    public UnionsStatus deleteUnionsMembersByMemsIds(Long[] membersIds) {
        //查询会员是否存在
        List<SysUnionMembers> sysUnionMembers = listByIds(Arrays.asList(membersIds));
        if (sysUnionMembers.size() == 0){
            return UnionsStatus.UNIONS_MEMBERS_NOT_EXIST;
        }
        //删除会员表
        boolean b = removeByIds(Arrays.asList(membersIds));
        if (!b){
            return UnionsStatus.UNIONS_MEMBERS_DELETE_FAIL;
        }
        //删除用户表
        List<Long> userIds = sysUnionMembers.stream().map(members-> members.getUserId()).collect(Collectors.toList());
        boolean b1 = sysUserService.removeByIds(userIds);
        if (!b1){
            return UnionsStatus.USER_DELETE_FAIL;
        }
        //删除用户角色表
        SysRole sysRole = new SysRole();
        sysRole.setRoleName(UnionConstants.UNION_CHAIRMAN);
        List<SysRole> sysRoles = sysRoleService.selectRoleList(sysRole);
        if (sysRoles.size() == 0){
            return UnionsStatus.UNION_CHAIRMAN_ROLE_NOT_EXIST;
        }
        int i = sysRoleService.deleteAuthUsers(sysRoles.get(0).getRoleId(),userIds.toArray(new Long[0]));
        if (i == 0){
            return UnionsStatus.ROLE_DELETE_FAIL;
        }
        return UnionsStatus.SUCCESS;
    }
}
